﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using Common;
using Model;
using PlcServer;
using Server;

namespace Server
{
    public class RecordServer : ModelBase
    {
        public event Action<string,float> RecordDoingEvent;
        /// <summary>
        /// 启动记录服务
        /// </summary>
        public void Start()
        {
            PlcHelper.PushTagValEvent += PlcHelper_PushTagValEvent;
        }

        private void PlcHelper_PushTagValEvent(string arg1, int arg2)
        {
            Record(arg1, arg2);
        }

        private int _flag;
        /// <summary>
        /// 动作标志位
        /// </summary>
        public int Flag
        {
            get { return _flag; }
            set { Set(ref _flag, value); }
        }
        /// <summary>
        /// 执行记录
        /// </summary>
        public void Record(string tagno, int tagval)
        {
            //只关注Trigger变量
            if (tagno != "Trigger")
            {
                return;
            }
            if (tagval == 0)
            {
                var rlt = PlcHelper.SetTagInt16("CMD", 0);
                if (!rlt.IsSuccess)
                {
                    Logger.WriteResultLog("下发命令失败");
                }

                return;
            }
            var tag = PlcHelper.PlcTag;
            Flag = 1;
            var mapVal = tag["BearingNo"];
            var result = Servers.DB.Select<Map>().Where(p => p.TagVal == mapVal).First();
            if (result == null)
            {
                Logger.WriteResultLog("记录信息失败，变量数值找不到对应的轴承编号");
                var rlt = PlcHelper.SetTagInt16("CMD", 99);
                if (!rlt.IsSuccess)
                {
                    Logger.WriteResultLog("写PLC变量失败");
                }
                return;
            }

            RecordResult recordResult = new RecordResult();
            recordResult.BearingNo = result.BearingNo;
            recordResult.OilNum = PlcHelper.GetValFloatInTime("OilNum").Content;
            recordResult.WorkingTime = DateTime.Now;
            try
            {
                var totalInfo = Servers.DB.Select<Bearings>().Any(p => p.BearingNo == recordResult.BearingNo);
                if (!totalInfo)
                {
                    float oilTotal = 0;
                    var totalObj =
                        Servers.DB.Ado.ExecuteScalar(
                            $"select sum(OilNum) from RecordResult where bearingno='{recordResult.BearingNo}'");
                    if (totalObj is DBNull)
                    {

                    }
                    else
                    {
                        oilTotal =Convert.ToSingle(totalObj);
                    }

                    int totalNum = 0;
                    var numObj =
                       Servers.DB.Ado.ExecuteScalar(
                            $"select count(*) from RecordResult where bearingno='{recordResult.BearingNo}' ");
                    if (numObj is DBNull)
                    {

                    }
                    else
                    {
                        totalNum = Convert.ToInt32(numObj);
                    }
                    var rlt = new Bearings()
                    {
                        BearingNo = recordResult.BearingNo,
                        OilTotal = oilTotal,
                        TotalProduct = totalNum,
                        TimeStamp = DateTime.Now,
                    };
                    var count = Servers.DB.Insert(rlt).ExecuteAffrows();
                }
            }
            catch (Exception ex)
            {
                Logger.WriteResultLog("插入数据总表失败", ex);
                return;
            }
            try
            {
                int count = -1;

                Servers.DB.Transaction(() =>
                {
                    count = Servers.DB.Insert(recordResult).ExecuteAffrows();
                    count = Servers.DB.Update<Bearings>().Set(p => p.OilTotal + recordResult.OilNum)
                        .Set(p => p.TotalProduct + 1).Set(p => p.TimeStamp, DateTime.Now)
                        .Where(p => p.BearingNo == recordResult.BearingNo).ExecuteAffrows() + 1;
                });

                if (count > 0)
                {
                    PlcHelper.SetTagInt16("CMD", 1);
                    RecordDoingEvent?.Invoke(recordResult.BearingNo,recordResult.OilNum);
                }
                else
                {
                    Logger.WriteResultLog("记录失败");
                }
            }
            catch (Exception ex)
            {
                Logger.WriteResultLog("记录数据失败", ex);
            }
        }
    }
}


